package com.example.community.controller.interceptor;

import com.example.community.entity.User;
import com.example.community.service.DataService;
import com.example.community.service.DiscussPostService;
import com.example.community.service.MessageService;
import com.example.community.service.UserService;
import com.example.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class MessageInterceptor implements HandlerInterceptor {

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private MessageService messageService;

    @Autowired
    private DataService dataService;

    @Autowired
    private UserService userService;

    @Autowired
    private DiscussPostService discussPostService;

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        if (user != null && modelAndView != null){
            int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(),null);
            int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(),null);
            modelAndView.addObject("allUnreadCount",letterUnreadCount + noticeUnreadCount);
//            long currentUV = dataService.calculateUV(new Date());
//            modelAndView.addObject("currentUV",currentUV);
//            long currentDAU = dataService.calculateDAU(new Date());
//            modelAndView.addObject("currentDAU",currentDAU);
//            modelAndView.addObject("date",new Date());
        }
        if (user != null && user.getType() == 1 && modelAndView != null){
            long currentUV = dataService.calculateUV(new Date());
            modelAndView.addObject("currentUV",currentUV);
            long currentDAU = dataService.calculateDAU(new Date());
            modelAndView.addObject("currentDAU",currentDAU);
            int totalUser = userService.totalUser();
            int totalPost = discussPostService.totalPost();
            modelAndView.addObject("totalUser",totalUser);
            modelAndView.addObject("totalPost",totalPost);
            modelAndView.addObject("date",new Date());
        }
    }
}
